<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="isMsgLogin = false" href="javascript:;" v-if="isMsgLogin">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="isMsgLogin = true" href="javascript:;" v-else>
        <i class="iconfont icon-shouji"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <div v-if="!isMsgLogin">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
        >
          <el-form-item prop="account">
            <el-input
              v-model="ruleForm.account"
              autocomplete="off"
              size="small"
              placeholder="请输入账号或手机号"
            >
              <template #prefix>
                <i class="iconfont icon-user"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="pass">
            <el-input
              v-model="ruleForm.pass"
              autocomplete="off"
              size="small"
              placeholder="请输入密码"
              type="password"
            >
              <template #prefix>
                <i class="iconfont icon-password"></i>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div v-else>
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          class="demo-ruleForm"
        >
          <el-form-item prop="phone">
            <el-input
              v-model="ruleForm.phone"
              autocomplete="off"
              size="small"
              placeholder="请输入手机号"
            >
              <template #prefix>
                <i class="iconfont icon-shouji"></i>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="message">
            <el-input
              v-model="ruleForm.message"
              autocomplete="off"
              size="small"
              placeholder="请输入验证码"
            >
              <template #prefix>
                <i class="iconfont icon-password"></i>
              </template>
              <template #suffix >
                <div :style="{color:'pink'}" >
                  <span v-if="isSendCode" @click="send">发送验证码</span>
                  <span v-else>{{countDown}}s</span>
                </div>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="form-item">
        <div class="agree">
          <XtxCheckbox v-model="form.isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
        <span class="isAgree" v-if="!form.isAgree"><i class="iconfont icon-jinggao"></i>请勾选登录协议</span>
      </div>
      <a href="javascript:;" class="btn" @click="submit">登录</a>
    </div>
    <div class="action">
       <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
            <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
          </a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref, watch } from "vue";
import { userAccountLogin, userMobileLoginMsg, userMobileLogin } from '@/api/user'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus';
export default {
  name: "LoginForm",
  data() {
    // 使用store
    const store = useStore()
    // 使用router
    const router = useRouter()
    // 使用route
    const route = useRoute()
    const isMsgLogin = ref(false);
      // 表单信息对象
    const form = reactive({
      isAgree: false,
    });

    // 切换登录方式的时候清空表单数据
    watch(isMsgLogin,() => {
      ruleForm.account = ""
      ruleForm.pass = ""
      ruleForm.phone = ""
      ruleForm.message = ""
    })
    // 登录提交
    const submit = () => {
      // 验证表单
      if (form.isAgree && /^[a-zA-Z]\w{5,19}$/.test(ruleForm.account) && /^\w{6,24}$/.test(ruleForm.pass)
          || form.isAgree && /^1[3-9]\d{9}$/.test(ruleForm.phone) && /^\d{6}$/.test(ruleForm.message))  {
        if (!isMsgLogin.value) {
          // 账号密码登录
          userAccountLogin({account:ruleForm.account, password:ruleForm.pass}).then(res => {
            // 成功
            console.log(res)
            // 1. 存储信息
            const { id, account, nickname, avatar, token, mobile } = res.result
            store.commit('user/setUser', { id, account, nickname, avatar, token, mobile })
            // 2. 提示
            ElMessage.success("登录成功")
            // 3. 跳转
            router.push(route.query.redirectUrl || '/')
          }).catch(err => {
            console.log(err);
            ElMessage.error({message:'登录失败'})
          })
        } else {
          // 短信登录
          userMobileLogin({mobile:ruleForm.phone, code:ruleForm.message}).then(res => {
            // 成功
            console.log(res)
            // 1. 存储信息
            const { id, account, nickname, avatar, token, mobile } = res.result
            store.commit('user/setUser', { id, account, nickname, avatar, token, mobile })
            // 2. 提示
            ElMessage.success("登录成功")
            // 3. 跳转
            router.push(route.query.redirectUrl || '/')
          }).catch(err => {
            console.log(err);
            ElMessage.error({message:'登录失败'})
          })
        }
      }
    }
    // 发送验证码
    const countDown = ref(60)
    const isSendCode = ref(true)
    const send = () => {
      // 显示倒计时
      isSendCode.value = false
      const countDownTime = setInterval(() => {
        if (countDown.value === 0) {
          clearInterval(countDownTime)
          // 倒计时结束，显示发送验证码，重置countDown
          isSendCode.value = true
          countDown.value = 60
        } else {
          countDown.value--
        }
      },1000)
      // 手机号验证
      if (/^1[3-9]\d{9}$/.test(ruleForm.phone)) {
        // 发送请求
        userMobileLoginMsg(ruleForm.phone).then(res => {
          console.log(res);
          ElMessage.success('发送成功')
        }).catch(err => {
          console.log(err);
          ElMessage.error("发送失败")
        })
      }
    }
    // 表单验证相关数据
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空"));
      } else if (!/^\w{6,24}$/.test(value)) {
        callback(new Error("密码是6-24个字符"));
      }
    };
    const checkAccount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("用户名不能为空"));
      } else if (!/^[a-zA-Z]\w{5,19}$/.test(value)) {
        callback(new Error("字母开头且6-20个字符"));
      }
    };
    const checkPhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号码不能为空"));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      }
    };
    const checkMessage = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("验证码不能为空"));
      } else if (!/^\d{6}$/.test(value)) {
        callback(new Error("验证码不正确"));
      }
    };
    const ruleForm = reactive({
      pass: "",
      account: "",
      phone: "",
      message: "",
    })
    const rules = reactive({
      pass: [{ validator: validatePass, trigger: "blur" }],
      account: [{ validator: checkAccount, trigger: "blur" }],
      phone: [{ validator: checkPhone, trigger: "blur" }],
      message: [{ validator: checkMessage, trigger: "blur" }],
    })
    return {
      submit,
      form,
      isMsgLogin,
      ruleForm,
      rules,
      countDown,
      isSendCode,
      send
    };
  },
};
</script>

<style scoped lang='less'>
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      position: relative;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .isAgree {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 1px;
        color: rgb(226, 74, 74);
        position: absolute;
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>